# encoding: utf-8
"""

    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lei.chang on '11/04/2025'
    comment: model层基础依赖
"""
from pydantic import BaseModel, Field, create_model
from typing import TypeVar
from project.lib.common import Global

T = TypeVar("T", bound=BaseModel)


def ResponseModel(cls: type[T]) -> type[T]:
    """
    :param cls:
    :return:
    """
    # 1. 构建 data 字段：默认值 None，类型就是原 cls
    fields = {
        'code': (int, Field(0, title='返回code', description='成功默认0, 非0失败')),
        'message': (str, Field('', title='失败原因')),
        'data': (cls | None, Field(None, title='业务数据'))
    }

    # 2. 生成新模型，类名保持可读
    class_name = f'{cls.__name__}Response{Global.count()}'
    NewModel = create_model(
        class_name,
        __base__=BaseModel,
        **fields
    )

    def _success(data: T | dict) -> NewModel:
        """成功响应"""
        return NewModel(code=0, message="", data=data)

    def _fail(code: int = -1, message: str = "", data: T | dict | None = None) -> NewModel:
        """失败响应"""
        return NewModel(code=code, message=message, data=data)

    NewModel.success = _success
    NewModel.fail = _fail

    return NewModel


@ResponseModel
class ApiResponse(BaseModel):
    """
    """
    pass
